export const requestDevice = async () => {
  if (!navigator.gpu) {
    window.alert(
      'WebGPU support is not available. A WebGPU capable browser is required to run this sample.'
    );
    throw new Error('WebGPU support is not available');
  }
  const adapter = await navigator.gpu.requestAdapter();

  if (!adapter) {
    throw new Error('adapter is not available');
  }

  const device = await adapter.requestDevice();

  return device;
};

type TypedArray = Float32Array | Uint16Array | Uint8Array | Uint32Array;

export function createGPUBuffer(device: GPUDevice, buffer: TypedArray, usage: number) {
  const gpuBuffer = device.createBuffer({
    size: buffer.byteLength,
    usage,
  });

  device.queue.writeBuffer(gpuBuffer, 0, buffer);

  return gpuBuffer;
}

export function shaderModuleFromCode(device: GPUDevice, code: string) {
  return device.createShaderModule({ code: code });
}

export function imagedataToImage(imagedata: ImageData, filename = 'image.png') {
  const canvas = document.createElement('canvas');
  const ctx = canvas.getContext('2d') as CanvasRenderingContext2D;
  canvas.width = imagedata.width;
  canvas.height = imagedata.height;
  ctx.putImageData(imagedata, 0, 0);

  const link = document.createElement('a');
  link.download = filename;
  link.href = canvas.toDataURL();
  link.click();
}
